<?php

namespace app\controllers\h5;

use app\controllers\h5\base\H5Controller;
use app\models\AdminSupplier;
use app\models\AwardResult;
use app\models\order\Order;
use app\models\Sms;
use app\models\system\SetApp;
use app\models\system\SetBasic;
use app\models\system\SetFlow;
use app\models\system\SetSms;
use app\models\user\User;
use app\models\user\User as Model;
use app\controllers\h5\services\User as Service;
use app\models\user\UserAccount;
use app\models\user\UserLevel;
use app\util\JWT;
use app\util\Util;
use Yii;

/**
 * Class UserController
 * @package app\controllers\h5
 */
class UserController extends H5Controller
{
    /**
     * Login
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionLogin()
    {
        $mobile = $this->post('mobile');
        $password = $this->post('password');

        if (!$mobile || !$password) {
            return $this->fail('请输入正确的用户名或者密码');
        }

        // login
        $user = Service::login($mobile, $password);
        if (!empty($user)) {
            if ($user['status'] == Model::$statusMapping['CLOSE']) {
                return $this->fail('正在关小黑屋中....');
            }

            // login ip
            $user->login_ip = Util::getClientIp();

            // 判断是公众号登录
            $user->is_wx = 1;
            $user->save();

            // generate token
            $token = JWT::createToken(
                [
                    'mobile' => $mobile,
                    'id' => $user['id'],
                ],
                Yii::$app->params['JWT_H5_KEY'],
                Yii::$app->params['JWT_H5_EXPIRED']
            );

            return $this->successEncode([
                'token' => $token,
                'id' => $user['id'],
            ], '登录成功');
        }

        return $this->fail('登录失败,请检查手机号码或者密码是否正确');
    }

    public function actionRegister()
    {
        $data = $this->post();

        // check user isExist
        $user = Model::findOne(['mobile' => $data['mobile']]);
        if ($user) {
            return $this->fail('此手机号码已经被注册了');
        }

        // referrer mobile or id
        if (isset($data['referrer']) && $data['referrer']) {
            $referrer = Model::find()
                ->where(['id' => $data['referrer']])
                ->orWhere(['mobile' => $data['referrer']])
                ->one();
            if (!$referrer) {
                return $this->fail('推荐人错误');
            }
            $data['referrer_id'] = $referrer->id;

            // check referrer
            // if (Service::checkReferrer($data['id'], $data['referrer_id'])) {
            //     return $this->fail('推荐人错误!!!');
            // }
        }

        // level
        $data['level'] = UserLevel::$keys['none'];
        $data['sort'] = 9999;

        // register
        $data = ['User' => $data];
        $model = new Model();
        if ($model->load($data) && $model->save()) {

            // user account
            $account = new UserAccount();
            $account->user_id = $model->id;
            if ($account->save()) {
                return $this->success('注册成功');
            }
        }


        return $this->fail('注册失败');
    }

    /**
     * Get user info
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionGetInfo()
    {
        $user = Service::getInfo($this->user->id);

        if ($user !== false) {
            // 等级设置
            $value = 0;
            if ($user['v5'] > 0) {
                $value = $user['v5'];
            }
            else if ($user['v4'] > 0) {
                $value = $user['v4'];
            }
            else if ($user['v3'] > 0) {
                $value = $user['v3'];
            }
            else if ($user['v2'] > 0) {
                $value = $user['v2'];
            }
            else if ($user['v1'] > 0) {
                $value = $user['v1'];
            }
            $level = UserLevel::find()
                ->where(['value' => $value])
                ->select(['display'])
                ->scalar();

            $user['vipLevel'] = $level;

            // svip 等级
            $str = [];
            if ($user['c1'] > 0) {
                $str[] = UserLevel::find()
                    ->where(['value' => $user['c1']])
                    ->select(['display'])
                    ->scalar();
            }
            if ($user['c2'] > 0) {
                $str[] = UserLevel::find()
                    ->where(['value' => $user['c2']])
                    ->select(['display'])
                    ->scalar();
            }

            $level = implode(' ', $str);
            $user['svipLevel'] = $level;

            return $this->successEncode($user);
        }

        return $this->fail('获取用户信息失败');
    }

    /**
     * Register agreement
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionAgreement()
    {
        $model = SetBasic::getLastOne();

        return $this->success($model->agreement);
    }

    /**
     * Get verify code
     *
     * @return array|string[]|\yii\web\Response
     * @throws \AlibabaCloud\Client\Exception\ClientException
     */
    public function actionVerifyCode()
    {
        $mobile = $this->post('mobile');
        if (!$mobile) {
            return $this->fail('请输入手机号码');
        }

        $set = SetSms::getLastOne();

        if (Sms::isSend($mobile)) {
            return $this->fail('请' . $set->timeout . '分钟之后再来...');
        }

        $start = pow(10, $set->len - 1);
        $end = pow(10, $set->len) - 1;
        $code = mt_rand($start, $end);
        if (Sms::generateCode($mobile, $code)) {
            $data = ['timeout' => $set->timeout];

            // is simulate
            if ($set->switch == 1) {
                $data['code'] = $code;
            }

            return $this->successEncode($data, '验证码已经成功发送,请注意查收!');
        }

        return $this->fail('获取验证码失败');
    }

    /**
     * Check verify
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionCheckVerify()
    {
        $mobile = $this->post('mobile');
        $code = $this->post('code');

        if (Sms::verify($mobile, $code)) {
            return $this->success();
        }

        return $this->fail('验证码错误');
    }

    /**
     * Forget password
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionForgetPassword()
    {
        $data = $this->post();

        $model = Model::findOne(['mobile' => $data['mobile']]);
        if (!$model) {
            return $this->fail('手机号码错误');
        }
        if ($model->status == Model::$statusMapping['CLOSE']) {
            return $this->fail('您已经被拉黑,无法修改');
        }

        $model->password = $data['password'];

        if ($model->save()) {
            return $this->success();
        }

        return $this->fail('操作失败');
    }

    /**
     * Change password
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionChangePassword()
    {
        $data = $this->post();

        if ($data['password'] != $data['password2']) {
            return $this->fail('两次密码不相同');
        }

        if (strlen($data['password']) < 6) {
            return $this->fail('长度不能小于6位');
        }

        $user = Model::findOne(['id' => $this->user->id]);

        if ($data['old_password'] != $user->password) {
            return $this->fail('旧密码错误');
        }

        $user->password = $data['password'];
        if ($user->save()) {
            return $this->success();
        }

        return $this->fail('操作失败');
    }

    /**
     * check wx login open
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionWxLogin()
    {
        $model = SetApp::getLastOne();

        return $this->successEncode($model->open_wx_login);
    }

    /**
     * Is it need referrer
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionNeedReferrer()
    {
        $model = SetFlow::getLastOne();

        return $this->successEncode($model->register_referrer);
    }

    // 保存地区
    public function actionSaveSupplierAddress()
    {
        $address_id = $this->post('address_id');
        $user = Model::findOne(['id' => $this->user->id]);
        $user->address_id = $address_id;
        if ($user->save()) {
            return $this->success();
        }
    }

    // 如果用户登录了, 则获取他的地区
    public function actionHasSupplierAddress()
    {
        $address_id = User::find()
            ->where(['id' => $this->user->id])
            ->select(['address_id'])
            ->scalar();

        return $this->success(['address_id' => $address_id]);
    }

    // 商家登录
    public function actionMerchantLogin()
    {
        $username = $this->post('username');
        $password = $this->post('password');

        $password = md5($password . Yii::$app->params['SUPPLIER_SALT']);

        // var_dump($username, $password);exit;

        $model = AdminSupplier::find()
            ->where(['status' => 1])
            ->andWhere(['username' => $username])
            ->andWhere(['password' => $password])
            ->one();
        if (!$model) {
            return $this->fail('用户名或者密码错误');
        }

        if ($model->is_shop == 0) {
            return $this->fail('您不是店家');
        }

        return $this->success(['id' => $model->id]);
    }

    // 中奖列表
    public function actionAwardList()
    {
        $s = $this->post('s');

        // var_dump($s);exit;

        $page = intval($this->post('page', $this->page));
        $pageSize = intval($this->post('pageSize', $this->pageSize));

        $query = AwardResult::find()
            ->where(['status' => 1]);

        if ($s > 1) {
            $query->andWhere(['user_id' => $this->user->id]);
        }

        $totalCount = $query->count();
        $totalPage = ceil($totalCount / $pageSize);

        $list = $query->orderBy(['update_time' => SORT_DESC])
            ->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->with(['award', 'user'])
            ->asArray()
            ->all();

        foreach ($list as &$item) {
            if ($item['user']['base64Image']) {
                $item['user']['avatar'] = $item['user']['base64Image'];
            }
        }

        return $this->successEncode([
            $this->list => $list,
            $this->totalCount => (int)$totalCount,
            $this->totalPage => $totalPage,
            $this->currentPage => $page
        ]);
    }

    // 我的抽奖码
    public function actionAwardSn()
    {
        $page = intval($this->post('page', $this->page));
        $pageSize = intval($this->post('pageSize', $this->pageSize));

        $query = Order::find()
            ->where(['award_status' => [1, 2]])
            ->andWhere(['user_id' => $this->user->id]);

        $totalCount = $query->count();
        $totalPage = ceil($totalCount / $pageSize);

        $list = $query->orderBy(['id' => SORT_DESC])
            ->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->asArray()
            ->all();

        return $this->successEncode([
            $this->list => $list,
            $this->totalCount => (int)$totalCount,
            $this->totalPage => $totalPage,
            $this->currentPage => $page
        ]);
    }
}